import { _decorator, Component, Node } from 'cc';
import { WEAPONTYPE } from './Weapon';
import { Monster } from './Monster';
import { EventManager, MyEvent } from '../AshFramework/Managers/EventManager';
const { ccclass, property } = _decorator;

@ccclass('WeaponManager')
export class WeaponManager extends Component {
    private static _instance: WeaponManager = null;
    public static get Instance(): WeaponManager {
        if (!WeaponManager._instance) {
            WeaponManager._instance = new WeaponManager();
        }
        return WeaponManager._instance;
    }

    /**
     *
     */
    constructor() {
        super();
        EventManager.on(MyEvent.REMOVE_MONSTER, this.removeMonster, this);
    }

    public mapMonster: Map<WEAPONTYPE, Node[]> = new Map();

    public addMonster(type: WEAPONTYPE, monster: Node) {
        //map中不存在type就创建他
        if (!this.mapMonster.get(type)) {
            this.mapMonster.set(type, [monster]);
        }
        if (this.getMonster(type, monster)) return;//已经存在
        this.mapMonster.get(type).push(monster);
    }

    getMonster(type: WEAPONTYPE, monster: Node) {
        return this.mapMonster.get(type).find(e => e === monster);
    }

    getMonsters(type: WEAPONTYPE) {
        if (!this.mapMonster.get(type)) {
            this.mapMonster.set(type, []);
        }
        return this.mapMonster.get(type);
    }

    removeMonster(monster: Node) {
        if (!monster || !monster.isValid) return;
        for (let arrMonster of this.mapMonster.values()) {
            let index = arrMonster.findIndex(e => e === monster);
            if (index != -1) {
                arrMonster.splice(index, 1);
            }
        }
    }

    removeMonsters(type: WEAPONTYPE) {
        this.mapMonster.delete(type);
    }

    logMap() {
        for (const [key, value] of this.mapMonster) {
            console.log(key, value);
        }
    }

    reinitialize(): void {
        this.mapMonster = new Map<WEAPONTYPE, Node[]>();
    }

}
